package cn.easybuy.servlet.pre;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.easybuy.entity.News;
import cn.easybuy.entity.Product;
import cn.easybuy.entity.ProductCategory;
import cn.easybuy.service.NewsService;
import cn.easybuy.service.ProductCategoryService;
import cn.easybuy.service.ProductService;
import cn.easybuy.service.impl.NewsServiceImpl;
import cn.easybuy.service.impl.ProductCategoryServiceImpl;
import cn.easybuy.service.impl.ProductServiceImpl;
public class HomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ProductCategoryService productCategoryService = new ProductCategoryServiceImpl();
	
	private ProductService productService = new ProductServiceImpl();
	
	private NewsService newsService = new NewsServiceImpl();
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String action = request.getParameter("action");
		if (action != null && action.length()>0) {
			switch (action) {
			case "index":
				index(request,response);
				break;
			default:
				response.sendRedirect("404.jsp");
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
	}

	private void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//获取菜单
		List<ProductCategory> listCategory = productCategoryService.findAll();
		
		request.getSession().setAttribute("allProductCategrory", listCategory);
		
		//获取1级菜单中的商品,将其放入map中
		Map<Integer, List<Product>> mapProduct = new HashMap<>();
		for (ProductCategory productCategory : listCategory) {
			if (productCategory.getType()==1) {
				List<Product> listProduct = productService.findProductsByCategoryId(productCategory.getId(),1,1,6).getList();
				
				mapProduct.put(productCategory.getId(), listProduct);
			}
		}
		
		//将该分类下的商品存在request作用域
		request.getSession().setAttribute("mapProductsOfCategory", mapProduct);
		
		//获取新闻信息
		List<News> newsList = newsService.findNewsList();
		
		request.setAttribute("newsList", newsList);
		
		//跳转到登录页面
		request.getRequestDispatcher("/pre/index.jsp").forward(request, response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
